package com.blyat.xsoft.auth.security;

import com.blyat.xsoft.auth.restful.entity.Authority;
import com.blyat.xsoft.auth.restful.entity.User;
import com.blyat.xsoft.auth.restful.service.AuthorityService;
import com.blyat.xsoft.auth.restful.service.UserService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;

/**
 * @Auther: syh
 * @Date: 2020/8/26
 * @Description:
 */
public class SecurityUserService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthorityService authorityService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        List<Authority> authorityList = authorityService.getByUserId(user.getId());
        if (authorityList != null && !authorityList.isEmpty()) {
            List<GrantedAuthority> grantedAuthorities = Lists.newArrayListWithExpectedSize(authorityList.size());
            authorityList.forEach(authority -> {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(
                        String.format("%s_%s", Constants.SECURITY_AUTH_PREFIX, authority.getId())
                );
                grantedAuthorities.add(grantedAuthority);
            });
            // 平台用户最基本角色
            grantedAuthorities.add(Constants.BASIC_GRANTED_AUTHORITY);
            user.setAuthorities(grantedAuthorities);
        }

        return user;

    }
}
